package com.sina.shop.manage.dao.business;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.Groom;
import com.sina.shop.domain.Status;
import com.sina.shop.domain.admin.Admin;
import com.sina.shop.domain.admin.Admin_;
import com.sina.shop.domain.business.Business;
import com.sina.shop.domain.business.Business_;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.TupleElement;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2018-01-04-15:36
 */
@Repository("businessManageDao")
public class BusinessManageDaoImpl extends ShopDataSourceDao implements BusinessManageDao {

    /*@Autowired
    private SCS sinaScs;*/

    @Override
    public Business getBusinessByName(String name) {
        String hql = "from Business where name=:name";
        return unique(hql, new String[]{"name"}, new Object[]{name});
    }

    @Override
    public int deleteBusiness(Long id) {
        String hql = "delete from Business b where b.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }


    @Override
    public List<Map<String, Object>> getBusinessList(Business business) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Business> root = criteriaQuery.from(Business.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    businessSelection(root)
            );

            Predicate predicate = businessPredicate(business, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Business_.admin)),
                    builder.asc(root.get(Business_.status))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (business.getPage() - 1) * business.getRows();

            query.setFirstResult(first);
            query.setMaxResults(business.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    /*protected final List<Map<String, Object>> mapWrapperFromTuple1(List<Tuple> tupleList, Class<?> mapClass) {

        if (!Map.class.isAssignableFrom(mapClass)) {
            throw new RuntimeException(String.format("mapClass[%s] is assignable from", mapClass));
        }

        List<Map<String, Object>> list = new ArrayList<>(tupleList.size());

        Map<String, Object> map;

        for (Tuple tuple : tupleList) {
            map = wrapperToMapFromTuple1(tuple, mapClass);
            list.add(map);
        }
        return list;
    }


    protected final Map<String, Object> wrapperToMapFromTuple1(Tuple tuple, Class<?> mapClass) {
        Map<String, Object> map;

        List<TupleElement<?>> elementList = tuple.getElements();

        map = createMap(
                (int) (elementList.size() / 0.75f)
                , mapClass);

        for (TupleElement<?> e : elementList) {
            if (e.getAlias().equals("photo")) {
                map.put(e.getAlias()
                        , SinaCloudUrlUtils.getBaseUrl(tuple.get(e).toString(), sinaScs)
                );
            } else {
                map.put(e.getAlias()
                        , tuple.get(e)
                );
            }
        }

        return map;
    }*/

    @Override
    public List<Map<String, Object>> getBusinessIdAndNameList() {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Business> root = criteriaQuery.from(Business.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    root.get(Business_.id).as(Long.class).alias("id"),
                    root.get(Business_.name).alias("name")
            );

            criteriaQuery.orderBy(
                    builder.asc(root.get(Business_.id))
            );
            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);

            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getBusinessCount(Business business) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Business> root = criteriaQuery.from(Business.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Business_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    businessPredicate(business, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param business
     * @param builder
     * @param root
     * @return
     */
    protected Predicate businessPredicate(Business business, CriteriaBuilder builder
            , Root<Business> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (business.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Business_.id), business.getLastId())
            );
        }

        if (business.getAdmin() != null) {
            list.add(
                    builder.equal(root.get(Business_.admin), business.getAdmin().getId())
            );
        }

        if (business.getName() != null) {
            list.add(
                    builder.equal(root.get(Business_.name), business.getName())
            );
        }

        if (business.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(Business_.createTime), business.getCreateStart())
            );
        }

        if (business.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(Business_.createTime), business.getCreateEnd())
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> businessSelection(Root<Business> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Business_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Business_.admin).alias("admin"));//
        list.add(root.get(Business_.name).alias("name"));
        list.add(root.get(Business_.photo).alias("photo"));
        list.add(root.get(Business_.credit).alias("credit"));

        list.add(root.get(Business_.notice).alias("notice"));//
        list.add(root.get(Business_.description).alias("description"));//
        list.add(root.get(Business_.createTime).alias("createTime"));
        list.add(root.get(Business_.updateTime).alias("updateTime"));
        list.add(root.get(Business_.isGroom).alias("isGroom"));

        list.add(root.get(Business_.status).alias("status"));
        return list;
    }

    @Override
    public int updateBusinessGroom(Long id, Groom isGroom) {
        String hql = "update Business b set b.isGroom = :isGroom where b.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("isGroom", isGroom);
            return query.executeUpdate();
        });
    }

    @Override
    public int deleteBusinessTab(Long id) {
        String hql = "update Business b set b.status = :status where b.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("status", Status.NOT_USE);
            return query.executeUpdate();
        });
    }
}
